﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using System.Text;
/// <summary>
/// des:字符串的静态拓展	
/// </summary>
public static class StringExtension {

    /// <summary>
    /// 首字母大写
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string UppercaseFirst(this string str)
    {
        switch (str.Length)
        {
            case 0:
                return "";
            case 1:
                return char.ToUpper(str[0]) + "";
            default:
                return char.ToUpper(str[0]) + str.Substring(1);

        }

    }

    /// <summary>
    /// 字符串是否为null或空
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static bool IsNullOrEmpty(this string str)
    {
        return string.IsNullOrEmpty(str);
    }


    /// <summary>
    /// 首字母小写
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string LowercaseFirst(this string str)
    {
        switch (str.Length)
        {
            case 0:
                return "";
            case 1:
                return char.ToLower(str[0]) + "";
            default:
                return char.ToLower(str[0]) + str.Substring(1);


        }

    }

    /// <summary>
    /// 获取首字母
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static string GetcaseFirst(this string str)
    {
        switch (str.Length)
        {
            case 0:
                return "";

            default:
                return char.ToLower(str[0]).ToString();

        }

    }

    /// <summary>
    /// 从字符串前面得到字符串指定长度字符串
    /// </summary>
    /// <param name="str"></param>
    /// <param name="index"></param>
    /// <returns></returns>
    public static string GetFrontStr(this string str, int index = 5)
    {
        if (str.Length < index)
        {
            return str;
        }
        else
        {
            return str.Substring(0, str.Length - index);
        }
    }
    /// <summary>
    /// 从字符串前面得到除去指定长度后的字符串
    /// </summary>
    /// <param name="str"></param>
    /// <param name="index"></param>
    /// <returns></returns>
    public static string GetFrontOtherStr(this string str, int index = 5)
    {
        if (str.Length < index)
        {
            return str;
        }
        else
        {
            return str.Substring(index, str.Length - index);
        }
    }

    /// <summary>
    /// 从字符串后面得到字符串指定长度字符串
    /// </summary>
    /// <param name="str"></param>
    /// <param name="index"></param>
    /// <returns></returns>
    public static string GetBackStr(this string str, int index = 5)
    {
        if (str.Length < index || (str.Length - index <= 0))
        {
            return str;
        }
        else
        {
            return str.Substring(str.Length - index, index);
        }
    }
    /// <summary>
    /// 从字符串后面得到字符串除去指定长度后的字符串
    /// </summary>
    /// <param name="str"></param>
    /// <param name="index"></param>
    /// <returns></returns>
    public static string GetBackOtherStr(this string str, int index = 5)
    {
        if (str.Length < index || (str.Length - index <= 0))
        {
            return str;
        }
        else
        {
            return str.Substring(0, str.Length - index);
        }
    }

    /// <summary>
    /// 将字符串转换为int
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static int ToInt(this string str)
    {
        int result = 0;
        if (!int.TryParse(str, out result))
        {
            //Debug.LogError("Can't Convert \"" + str + "\" to Int !");
        }
        return result;
    }

    public static T ConvertTo<T>(this string str)
    {
        T result = default(T);
        try
        {
            result = (T)System.Convert.ChangeType(str, typeof(T));
        }
        catch (System.Exception)
        {
            //Debug.LogError("Can't Convert \"" + str + "\" to " + typeof(T) + " !" + "\r\n" + e);
        }
        return result;
    }
    /// <summary>
    /// 将字符串转换为flaot
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static float ToFloat(this string str)
    {
        float result = 0;

        if (!float.TryParse(str.Replace("f", ""), out result))
        {
            //Debug.LogError("Can't Convert \"" + str + "\" to Float !");
        }
        return result;
    }

    public static byte[] ToByte(this string str)
    {
        return Encoding.UTF8.GetBytes(str);
    }

    public static string ToChinese(this string str)
    {
        switch (str)
        {
            case "ATT":
                str = "<color=red>攻击</color>: ";
                break;
            case "Criticalhitrate":
                str = "<color=red>暴击</color>: ";
                break;
            case "Criticaldamage":
                str = "<color=red>暴伤</color>: ";
                break;
            case "MaxHp":
                str = "<color=red>血量</color>: ";
                break;
            case "DEF":
                str = "<color=red>防御</color>: ";
                break;
            case "CurrentHp":
                str = "<color=red>当前血量</color>: ";
                break;
            case "AttackCheckDistance":
                str = "<color=red>攻击距离</color>: ";
                break;
            case "AttackCheckPoint":
                str = "<color=red>攻击点</color>: ";
                break;
            case "MoveSpeed":
                str = "<color=red>移动速度</color>: ";
                break;
            case "AttackSpeed":
                str = "<color=red>攻击速度</color>: ";
                break;
            default:
                str = "<color=red>" + str + "</color>: ";
                break;


        }
        return str;
    }

    public static bool Contains(this string str, params string[] var)
    {
        if (var == null)
        {
            return false;
        }
        for (int i = 0; i < var.Length; i++)
        {
            if (str.Contains(var[i]))
            {
                return true;
            }
        }
        return false;
    }
    /// <summary>
    /// 去除特定的项后是否为NULL 或0
    /// </summary>
    /// <param name="str"></param>
    /// <param name="var"></param>
    /// <returns></returns>
    public static bool RemoveContains(this List<string> str, params string[] var)
    {
        if (var == null|| str== null)
        {
            return false;
        }
        List<string> cont = new List<string>();
        for (int i = 0; i < var.Length; i++)
        {
            string temp= str.Find(v=>v.Contains(var[i]));
            if(temp!=null)
            {
                cont.Add(temp);
            }
        }
        return (str.Count- cont.Count)>0;
    }

    public static bool Contains(this string str, List<string> expand,bool replace=true)
    {
        
       
        if (expand == null)
        {
            return false;
        }
        for (int i = 0; i < expand.Count; i++)
        {
            if (str.Contains(replace?System.Text.RegularExpressions.Regex.Replace(expand[i].Replace("_", "").Replace("-", ""), @"\d", ""): expand[i]))
            {
                return true;
            }
        }
        return false;
    }

    public static bool Contains(this string str,List<string> expand, params string[] var)
    {
        if (var == null)
        {
            return false;
        }
        for (int i = 0; i < var.Length; i++)
        {
            if (str.Contains(var[i]))
            {
                return true;
            }
        }
        if(expand==null)
        {
            return false;
        }
        for (int i = 0; i < expand.Count; i++)
        {
            if (str.Contains(expand[i]))
            {
                return true;
            }
        }
        return false;
    }

    /// <summary>
    /// 是否存在汉字
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static bool HaveChinese(this string str)
    {
        if (str.IsNullOrEmpty())
        {
            return false;
        }
        for (int i = 0; i < str.Length; i++)
        {
            //if (System.Text.RegularExpressions.Regex.IsMatch(str[i].ToString(), @"[\u4e00-\u9fbb]+{1}"))
            if ((int)str[i] > 127)
            {
                return true;
            }

        }
        return false;
    }
    /// <summary>
    /// 是否存在数字
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static bool HaveNumber(this string str)
    {
        bool result = false;
        for (int i = 0; i < str.Length; i++)
        {
            if (Char.IsNumber(str, i))
            {
                result = false;
            }
            else
            {
                result = true;
            }
        }
        return !result;
    }
    /// <summary>
    /// 全是数字
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static bool AllNumber(this string str)
    {
       
        for (int i = 0; i < str.Length; i++)
        {
            if (!Char.IsNumber(str, i))
            {
                return false;
            }
           
        }
        return true;
    }

    /// <summary>
    /// 全是汉字
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public static bool AllChinese(this string str)
    {
        for (int i = 0; i < str.Length; i++)
        {
            //if (System.Text.RegularExpressions.Regex.IsMatch(str[i].ToString(), @"[\u4e00-\u9fbb]+{1}"))
            if ((int)str[i] < 127)
            {
                return false;
            }

        }
        return true;
    }

    /// <summary>
    /// 通过字符串获取枚举
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="str"></param>
    /// <returns></returns>
    public static T GetEnumByString<T>(this string str)
    {
        if (str.IsNullOrEmpty())
        {
            return default(T);
        }
        try
        {
            return (T)Enum.Parse(typeof(T), str);
        }
        catch (Exception)
        {
            return default(T);
        }

    }

    #region 删除文件名或路径的特殊字符 以及拓展名

    private class ClearPathUnsafeList
    {
        public static readonly string[] unSafeStr = { "/", "\\", ":", "*", "?", "\"", "<", ">", "|", " " };
    }

    /// <summary>
    /// 删除文件名或路径的特殊字符
    /// </summary>
    /// <param name="t"></param>
    /// <returns></returns>
    public static string ClearPathUnsafe(this string t)
    {
        foreach (string s in ClearPathUnsafeList.unSafeStr)
        {
            t = t.Replace(s, "");
        }

        return t;
    }

    /// <summary>
    /// 删除字符串的扩展名
    /// </summary>
    public static string RemoveStringExt(this string file)
    {
        if (file == null || file.Length == 0)
            return "";
        int i = file.LastIndexOf('.');
        if (i < 0)
            return file;
        return file.Substring(0, i);
    }
    #endregion
    /// <summary>
    /// 切割字符串
    /// </summary>
    /// <param name="sourceString"></param>
    /// <param name="splitString"></param>
    /// <returns></returns>
    public static string[] SplitWithString(this string sourceString, string splitString)
    {
        string tempSourceString = sourceString;
        List<string> arrayList = new List<string>();
        string s = string.Empty;
        while (sourceString.IndexOf(splitString) > -1)  //切割
        {
            s = sourceString.Substring(0, sourceString.IndexOf(splitString));
            sourceString = sourceString.Substring(sourceString.IndexOf(splitString) + splitString.Length);
            arrayList.Add(s);
        }
        arrayList.Add(sourceString);
        return arrayList.ToArray();
    }

    /// <summary>
    /// 一定字符后添加符号
    /// </summary>
    /// <param name="sourceString"></param>
    /// <param name="index"></param>
    /// <returns></returns>
    public static string AddSymbol(this string sourceString,int index)
    {
       
        if(sourceString.IsNullOrEmpty()|| sourceString.Length< index )
        {
            return sourceString;
        }
       
        for (int i = 0; i < sourceString.Replace("\n", "").Length; i++)
        {
            if(i%index==0)
            {
                sourceString=sourceString.Insert(i, "\n");

            }
        }
        return sourceString;
    }

    /// 将原始字串转换为unicode,格式为\u....\u....
    /// </summary>
    /// <param name="srcText"></param>
    /// <returns></returns>
    public static string StringToUnicode(this string srcText)
    {
        string dst = "";
        char[] src = srcText.ToCharArray();
        for (int i = 0; i < src.Length; i++)
        {
            byte[] bytes = Encoding.Unicode.GetBytes(src[i].ToString());
            string str = @"\u" + bytes[1].ToString("X2") + bytes[0].ToString("X2");
            dst += str;
        }
        return dst;
    }
    /// <summary>
    /// 从指定字符串中的指定位置处开始读取一行。
    /// </summary>
    /// <param name="rawString">指定的字符串。</param>
    /// <param name="position">从指定位置处开始读取一行，读取后将返回下一行开始的位置。</param>
    /// <returns>读取的一行字符串。</returns>
    public static string ReadLines(this string rawString, ref int position)
    {
        if (position < 0)
        {
            return null;
        }

        int length = rawString.Length;
        int offset = position;
        while (offset < length)
        {
            char ch = rawString[offset];
            switch (ch)
            {
                case '\r':
                case '\n':
                    if (offset > position)
                    {
                        string line = rawString.Substring(position, offset - position);
                        position = offset + 1;
                        if ((ch == '\r') && (position < length) && (rawString[position] == '\n'))
                        {
                            position++;
                        }

                        return line;
                    }

                    offset++;
                    position++;
                    break;

                default:
                    offset++;
                    break;
            }
        }

        if (offset > position)
        {
            string line = rawString.Substring(position, offset - position);
            position = offset;
            return line;
        }

        return null;
    }

    #region  DES字符串加密解密

    private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
    /// <summary>
    /// DES加密字符串
    /// </summary>
    /// <param name="encryptString">待加密的字符串</param>
    /// <param name="key">加密密钥,要求为8位</param>
    /// <returns>加密成功返回加密后的字符串，失败返回源串</returns>
    public static string EncryptDES(this string encryptString, string key = "45131929")
    {
        try
        {
            byte[] rgbKey = Encoding.UTF8.GetBytes(key.Substring(0, 8));
            byte[] rgbIV = Keys;
            byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
            DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
            MemoryStream mStream = new MemoryStream();
            CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            cStream.Close();
            return Convert.ToBase64String(mStream.ToArray());
        }
        catch
        {
            Debug.Print("StringEncrypt/EncryptDES()/ Encrypt error!");
            return encryptString;
        }
    }

    /// <summary>
    /// DES解密字符串
    /// </summary>
    /// <param name="decryptString">待解密的字符串</param>
    /// <param name="key">解密密钥,要求为8位,和加密密钥相同</param>
    /// <returns>解密成功返回解密后的字符串，失败返源串</returns>
    public static string DecryptDES(this string decryptString, string key = "45131929")
    {
        try
        {
            byte[] rgbKey = Encoding.UTF8.GetBytes(key);
            byte[] rgbIV = Keys;
            byte[] inputByteArray = Convert.FromBase64String(decryptString);
            DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
            MemoryStream mStream = new MemoryStream();
            CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
            cStream.Write(inputByteArray, 0, inputByteArray.Length);
            cStream.FlushFinalBlock();
            cStream.Close();
            return Encoding.UTF8.GetString(mStream.ToArray());
        }
        catch
        {
            Debug.Print("StringEncrypt/DecryptDES()/ Decrypt error!");
            return decryptString;
        }
    }

    #endregion

    #region  AES字符串加密解密
    /// <summary>
    ///  AES 加密
    /// </summary>
    /// <param name="str">明文（待加密）</param>
    /// <param name="key">密文</param>
    /// <returns></returns>
    public static string AesEncrypt(this string str, string key)
    {
        if (string.IsNullOrEmpty(str)) return null;
        Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str);

        RijndaelManaged rm = new RijndaelManaged
        {
            Key = Encoding.UTF8.GetBytes(key),
            Mode = CipherMode.ECB,
            Padding = PaddingMode.PKCS7
        };

        ICryptoTransform cTransform = rm.CreateEncryptor();
        Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }
    /// <summary>
    ///  AES 解密
    /// </summary>
    /// <param name="str">明文（待解密）</param>
    /// <param name="key">密文</param>
    /// <returns></returns>
    public static string AesDecrypt(this string str, string key)
    {
        if (string.IsNullOrEmpty(str)) return null;
        Byte[] toEncryptArray = Convert.FromBase64String(str);

        RijndaelManaged rm = new RijndaelManaged
        {
            Key = Encoding.UTF8.GetBytes(key),
            Mode = CipherMode.ECB,
            Padding = PaddingMode.PKCS7
        };

        ICryptoTransform cTransform = rm.CreateDecryptor();
        Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);

        return Encoding.UTF8.GetString(resultArray);
    }
    #endregion
    //#region 自定义加密解密
    ///// <summary>
    ///// 自定义加密
    ///// </summary>
    ///// <param name="value"></param>
    ///// <returns></returns>
    //public static string CustomEncrypt(this string value)
    //{
    //    string newValue = null;

       
       
    //    if ((!value.IsNullOrEmpty() && value.Length==10)&& value.AllNumber())
    //    {
    //        string[] temp;
    //        for (int i = 0; i < value.Length; i++)
    //        {
    //            temp = SecretorderConfig.Get(value.Substring(i, 1).ToInt()).secretorderStr.Split(',');
    //            newValue+= temp[(int)RandomHelper.RandomNumber(0, temp.Length)];
    //        }
    //        temp = SecretorderConfig.Get(10).secretorderStr.Split(',');
    //        newValue=newValue.Insert((int)RandomHelper.RandomNumber(1, newValue.Length-1), temp[(int)RandomHelper.RandomNumber(0, temp.Length)]);
    //        newValue=newValue.Insert((int)RandomHelper.RandomNumber(1, newValue.Length-1), temp[(int)RandomHelper.RandomNumber(0, temp.Length)]);
    //        int index = 6;
    //        for (int i = 0; i < newValue.Length; i++)
    //        {
    //            if (RandomHelper.GetRandomResoult(30, 100)&& index>0)
    //            {
    //                index -= 1;
    //                newValue = newValue.Replace(newValue[i], char.ToUpper(newValue[i]));
    //            }
    //        }
    //    }
       
    //    return newValue;
    //}
    ///// <summary>
    ///// 自定义解密
    ///// </summary>
    ///// <param name="value"></param>
    ///// <returns></returns>
    //public static string CustomDecrypt(this string value)
    //{
    //    string newvalue = null;
    //    if(!value.IsNullOrEmpty()&& !value.HaveChinese() && !value.HaveNumber()&& value.Length==12)
    //    {
    //        value = value.ToLower().Replace("c", "").Replace("h", "").Replace("e", "").Replace("n", "").Replace("g", "").Replace("s", "");
    //        for (int i = 0; i < value.Length; i++)
    //        {
    //            newvalue+=SecretorderConfig.config.datas.Find(v => v.secretorderStr.Contains(value[i].ToString())).id;
    //        }
    //    }
    //    return newvalue;
    //}
    
    ////public static bool CheckSecretorderAvailable(this string value)
    ////{
    ////    if(SecretorderConfig.config.datas.Find(v=>v.secretorderStr==value)==null)
    ////    {
    ////        return false;
    ////    }
    ////    else
    ////    {
    ////        //检测日期
    ////        string temp= value.CustomDecrypt();
          
    ////        DateTime lastTime = Convert.ToDateTime(string.Format("{0}/{1}/{2}", "20"+ temp.Substring(4,2), temp.Substring(2, 2), temp.Substring(0,2)));
    ////        DateTime nextTime = Convert.ToDateTime(string.Format("{0}/{1}/{2}", "20" + temp.Substring(4, 2), temp.Substring(6, 2), temp.GetBackStr(2)));
    ////        //通过DateTIme.Compare()进行比较（）
    ////        int last = DateTime.Compare(lastTime, GameFacade.Instance.dateTime);
    ////        int next= DateTime.Compare(GameFacade.Instance.dateTime, nextTime);
            
    ////        //t1> t2
    ////        if (last <= 0 && next <= 0)
    ////        {
    ////            //TODO：检测玩家是否使用过
    ////            return true;
    ////        }
            
    ////    }
    ////    return false;
    ////}
    //#endregion
}
